import logging
import os

from pdf2docx import Converter


def pdf_to_word(pdf_path, word_path, info=False):
    if not info:
        logging.disable(logging.CRITICAL)  # 禁用所有日志

    # 检查输出的Word文件是否存在，如果存在则删除
    if os.path.exists(word_path):
        os.remove(word_path)

    try:
        cv = Converter(pdf_path)  # 创建一个转换器对象
        cv.convert(word_path, start=0, end=None)  # 将PDF转换为Word
        cv.close()  # 关闭转换器
        print(f"Successfully converted '{pdf_path}' to '{word_path}'.")

    except FileNotFoundError:
        print(f"[Error] No such file: {pdf_path}")
    except Exception as e:
        print(f"[Error] An unexpected error occurred: {e}")
    finally:
        logging.disable(logging.NOTSET)  # 恢复所有日志


# 示例用法
if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO)  # 设置日志级别
    pdf_file = 'PDF/tongyi_logo_pdf/tongyi_logo_ptw2.pdf'  # 输入你的PDF文件路径
    word_file = 'word/tongyi_logo_word/tongyi_logo_ptw2.docx'  # 输出的Word文件路径
    pdf_to_word(pdf_file, word_file, info=False)
